﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Collections;
using System.IO;

namespace CnGine.CodeGenerator.Forms
{
    public partial class FormMain : Form
    {

        #region [属性]
        private string _server = "";
        //服务器链接字符串
        private string _serverConnection = "";
        //数据库的链接字符串
        private string connection = "";
        /// <summary>
        /// 设置服务名称
        /// </summary>
        public string Server
        {
            set { this._server = value; }
            get { return this._server; }
        }
        /// <summary>
        /// 设置服务器信息
        /// </summary>
        public string ServerConnection
        {
            set { this._serverConnection = value; }
            get { return this._serverConnection; }
        }
        //数据库列表信息
        private List<Models.DataBase> DBS = new List<Models.DataBase>();
        private List<Models.Table> TBS = new List<Models.Table>();

        #endregion

        #region [初始化操作]
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

            btnTemplate.Visible = false;

            Succ("");
            lblServer.Text = Server;
            btnShengcheng.Enabled = false;
            try
            {
                //获取所有的数据库
                DBS = new Help.SQLHelper().GetDataBase(ServerConnection);
                cbDataBase.DataSource = DBS;
                cbDataBase.DisplayMember = "Name";
                cbDataBase.ValueMember = "Name";
                cbDataBase.SelectedIndex = -1;
            }
            catch
            {
                Error("错误：服务器连接错误。");
            }
            //绑定输出
            txtOutPut.Text = Help.DTEHelper.GetProjectPath();
            //绑定模板信息
            LoadTemplate();
        }

        /// <summary>
        /// 加载模板信息
        /// </summary>
        public void LoadTemplate()
        {
            string templateDir = Help.CommHelper.GetAssemblyPath() + @"\Templates\";
            DirectoryInfo mydir = new DirectoryInfo(templateDir);
            foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
            {
                if (fsi is FileInfo)
                {
                    FileInfo fi = (FileInfo)fsi;
                    cbTemplate.Items.Add(fi.Name);
                }
            }
            //默认选中第一个模板
            cbTemplate.SelectedIndex = 0;
        }
        #endregion

        #region [成功和错误处理]
        public void Error(string msg)
        {
            lblMsg.ForeColor = Color.Red;
            lblMsg.Text = string.Format("{0}", msg);
        }
        public void Succ(string msg)
        {
            lblMsg.ForeColor = Color.Green;
            lblMsg.Text = string.Format("{0}", msg);

        }
        #endregion

        #region [针对表事件]

        ArrayList tableLeft = new ArrayList();
        ArrayList tableRight = new ArrayList();

        public void InitListBox()
        {
            lbTableLeft.Items.Clear();
            lbTableRight.Items.Clear();

            tableLeft.Sort();
            tableRight.Sort();
            //绑定左边的表
            foreach (string item in tableLeft)
                lbTableLeft.Items.Add(item);
            //绑定右边的表
            foreach (string item in tableRight)
                lbTableRight.Items.Add(item);

            //判断是否可以生成代码
            if (tableRight.Count > 0)
                btnShengcheng.Enabled = true;
            else
                btnShengcheng.Enabled = false;
        }
        private void cbDataBase_SelectedIndexChanged(object sender, EventArgs e)
        {
            string database = "";
            if (cbDataBase.SelectedValue != null) database = cbDataBase.SelectedValue.ToString();
            Models.DataBase db = DBS.Find(delegate(Models.DataBase bb) { return bb.Name == database; });

            if (db != null)
            {
                try
                {
                    //设置数据库的链接字符串
                    connection = string.Format("{0}database={1};", ServerConnection, database);
                    //根据数据库链接字符串获取所有表
                    TBS = new Help.SQLHelper().GetTable(connection);
                    //初始化一下
                    tableLeft = new ArrayList();
                    tableRight = new ArrayList();
                    foreach (Models.Table item in TBS)
                    {
                        tableLeft.Add(item.Name);
                    }
                    InitListBox();
                }
                catch (Exception t)
                {
                    throw t;
                }
            }
        }

        private void btnToRightAll_Click(object sender, EventArgs e)
        {
            foreach (string item in tableLeft)
            {
                if (tableRight.IndexOf(item) == -1)
                {
                    tableRight.Add(item);
                }
            }
            tableLeft.Clear();
            InitListBox();
        }
        private void btnToRight_Click(object sender, EventArgs e)
        {
            if (lbTableLeft.SelectedItem != null)
            {
                string table = lbTableLeft.SelectedItem.ToString();
                //移到右边
                if (tableRight.IndexOf(table) == -1)
                {
                    tableRight.Add(table);
                }
                tableLeft.Remove(table);
                InitListBox();
            }

        }

        private void btnToLeft_Click(object sender, EventArgs e)
        {
            if (lbTableRight.SelectedItem != null)
            {
                string table = lbTableRight.SelectedItem.ToString();
                //移到右边
                if (tableLeft.IndexOf(table) == -1)
                {
                    tableLeft.Add(table);
                }
                tableRight.Remove(table);

                InitListBox();
            }
        }

        private void btnToLeftAll_Click(object sender, EventArgs e)
        {
            foreach (string item in tableRight)
            {
                if (tableLeft.IndexOf(item) == -1)
                {
                    tableLeft.Add(item);
                }
            }
            tableRight.Clear();
            InitListBox();
        }
        //双击左边
        private void lbTableLeft_DoubleClick(object sender, EventArgs e)
        {
            btnToRight_Click(sender, e);
        }
        //双击左边
        private void lbTableRight_DoubleClick(object sender, EventArgs e)
        {
            btnToLeft_Click(sender, e);
        }
        #endregion


        private void btnBack_Click(object sender, EventArgs e)
        {
            Forms.FormDB fm = new FormDB();
            this.Hide();
            fm.ShowDialog();

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnShengcheng_Click(object sender, EventArgs e)
        {
            try
            {
                //重新获取表信息以及列信息
                TBS = new Help.SQLHelper().GetTableAndColumn(connection);
                //获取选择的表
                ArrayList listTable = new ArrayList();
                foreach (string item in lbTableRight.Items)
                {
                    listTable.Add(item);
                }
                string qianzhui = txtQianzhui.Text.Trim();
                string templateName = cbTemplate.SelectedItem.ToString();
                string outputPath = txtOutPut.Text.Trim();

                //生成代码
                Help.CodeGenerator.CreateCsCode(outputPath, templateName, TBS, listTable, qianzhui);
                //生成成功之后关掉窗口
                Succ("代码已生成成功。" + System.DateTime.Now.ToString());
                this.Hide();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void btnTemplate_Click(object sender, EventArgs e)
        {
            FormTemplate frm = new FormTemplate();
            frm.ShowDialog();
        }
    }
}

